<template>
  <div>
    <el-card class="box-card ">
      <div class="content">

        <el-row :gutter="8"
                type="flex"
                align="middle"
                style="margin-bottom:10px;flex-wrap:wrap;align-items: between;">
          <el-col :span="1.5">
            角色名称
          </el-col>
          <el-col :span="40">
            <el-input size="small"
                      v-model="queryParams.roleName"
                      placeholder="请输入角色名称"></el-input>
          </el-col>
          <el-col :span="1.5">
            权限字符
          </el-col>
          <el-col :span="40">
            <el-input size="small"
                      v-model="queryParams.roleKey"
                      style="width: 200px"
                      placeholder="请输入权限字符"></el-input>
          </el-col>

          <el-col :span="1.5">
            状态
          </el-col>
          <el-col :span="40">
            <el-select placeholder="请选择"
                       size="small"
                       v-model="queryParams.status">

              <el-option label="正常"
                         :value="0">
              </el-option>
              <el-option label="停用"
                         :value="1">
              </el-option>

            </el-select>

          </el-col>
          <el-col :span="1.5">
            创建时间
          </el-col>
          <el-col :span="30">
            <el-date-picker type="daterange"
                            size="small"
                            style="width:200px"
                            range-separator="至"
                            value-format="yyyy-MM-dd"
                            start-placeholder="开始日期"
                            end-placeholder="结束日期">
            </el-date-picker>
          </el-col>
          <el-col :span="1.5">
            <el-button size="mini"
                       type="primary"
                       icon="el-icon-search"
                       @click="getData()">搜索</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button icon='el-icon-refresh'
                       size="mini"
                       @click="refreshTable()">重置</el-button>
          </el-col>
        </el-row>
        <div class="btnList">
          <el-row :gutter="8"
                  type="flex"
                  align="middle"
                  class="btn_nav">
            <el-col :span="1.5">
              <el-button size="mini"
                         type="primary"
                         icon="el-icon-plus"
                         plain
                         @click="addXqq">新增</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button size="mini"
                         type="success"
                         icon="el-icon-edit"
                         plain
                         @click="updatadata"
                         :disabled='checkItem.length!=1'>修改</el-button>
            </el-col>

            <el-col :span="1.5">
              <el-button size="mini"
                         type="danger"
                         icon="el-icon-delete"
                         plain
                         :disabled='checkItem.length==0'
                         @click="delMore">删除</el-button>
            </el-col>

            <el-col :span="1.5">
              <el-button size="mini"
                         type="warning"
                         icon="el-icon-download"
                         @click="exportdata"
                         plain>导出</el-button>
            </el-col>
          </el-row>

          <el-row :gutter="8"
                  type="flex"
                  align="middle"
                  class="btn_nav">

            <el-col :span="1.5">
              <el-button size="mini"
                         icon="el-icon-search"
                         circle></el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button @click="refreshTable"
                         size="mini"
                         icon="el-icon-refresh"
                         circle></el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button @click="refreshTable"
                         size="mini"
                         icon="el-icon-menu"
                         circle></el-button>
            </el-col>
          </el-row>
        </div>
        <el-table :data="tableData"
                  v-loading="loading"
                  style="width: 100%"
                  :header-cell-style="{background:'#f8f8f9','text-align':'center'}"
                  @selection-change="handleSelectionChange"
                  :cell-style="{'text-align':'center'}">
          <el-table-column width="80"
                           type="selection">
          </el-table-column>
          <el-table-column prop="roleId"
                           width="80"
                           label="角色编号">
          </el-table-column>
          <el-table-column prop="roleName"
                           width="80"
                           label="角色名称">
          </el-table-column>
          <el-table-column prop="nickName"
                           width="80"
                           label="用户昵称">
          </el-table-column>

          <el-table-column prop="roleKey"
                           width="80"
                           label="权限字符">

          </el-table-column>
          <el-table-column prop="roleSort"
                           width="80"
                           label="显示顺序">
          </el-table-column>
          <el-table-column prop="status"
                           width="60"
                           label="状态">
            <template slot-scope="scope">
              <el-switch v-model="scope.row.status"
                         @change="changeStatus($event,scope.row)"
                         inactive-value="1"
                         active-value="0">
              </el-switch>
            </template>
          </el-table-column>
          <el-table-column prop="createTime"
                           label="创建时间">
          </el-table-column>

          <el-table-column label="操作">
            <template v-slot="data">
              <el-button icon="el-icon-edit"
                         type="text"
                         @click="updateHandler(data.row.roleId)">修改</el-button>
              <el-button v-if="data.row.userId!=1"
                         icon="el-icon-circle-check"
                         type="text"
                         @click="roleKeyHandler(data.row.roleId)">数据权限</el-button>
              <el-button v-if="data.row.userId!=1"
                         icon="el-icon-delete"
                         type="text"
                         @click="deleteHandler(data.row.roleId)">删除</el-button>
            </template>

          </el-table-column>

        </el-table>
        <div class="page"
             v-show="total!=0">
          <el-pagination background
                         @size-change="handleSizeChange"
                         @current-change="handleCurrentChange"
                         :current-page="queryParams.pageNum"
                         :page-sizes="[3, 5, 9, 10]"
                         :page-size="queryParams.pageSize"
                         layout="total, sizes, prev, pager, next, jumper"
                         :total="total">
          </el-pagination>
        </div>

      </div>
    </el-card>
    <div>
      <el-dialog :title="flag?'添加角色':'修改角色'"
                 @closed="closed"
                 :visible.sync="dialogVisible"
                 width="40%">
        <el-form :model="formData"
                 ref="ruleForm"
                 label-width="80px">
          <el-form-item label="角色名称"
                        prop="postName">
            <el-input v-model="formData.roleName"
                      placeholder="角色名称"></el-input>
          </el-form-item>

          <el-form-item label="权限字符"
                        prop="postCode">
            <el-input v-model="formData.roleKey"
                      placeholder="请输入权限字符"></el-input>
          </el-form-item>

          <el-form-item prop="postSort"
                        label="角色顺序">
            <el-input-number controls-position="right"
                             v-model="formData.roleSort"
                             :min="0"
                             :max="10000000"></el-input-number>
          </el-form-item>
          <el-form-item label="状态">
            <template>
              <el-radio v-model="formData.status"
                        label="0">正常</el-radio>
              <el-radio v-model="formData.status"
                        label="1">停用</el-radio>
            </template>

          </el-form-item>
          <el-form-item label="菜单权限">
            <el-checkbox v-model="expand">展开/折叠</el-checkbox>
            <el-checkbox v-model="selectAll">全选/全不选</el-checkbox>
            <el-checkbox v-model="strictly">父子联动</el-checkbox>
            <el-tree :data="treeList"
                     show-checkbox
                     node-key="id"
                     ref="tree"
                     @check-change="treeChange"
                     :check-strictly="!strictly"
                     :default-expand-all="false"
                     style="border:1px solid #e5e6e7"
                     highlight-current
                     :props="defaultProps">
            </el-tree>
          </el-form-item>
          <el-form-item label="备注">
            <el-input type="textarea"
                      v-model="formData.remark"
                      placeholder="备注"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer"
              class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary"
                     @click="update">确 定</el-button>
        </span>
      </el-dialog>
    </div>

    <div>
      <el-dialog title="分配权限名称"
                 :visible.sync="roleKey"
                 width="40%">
        <el-form :model="roleData"
                 label-width="80px">
          <el-form-item label="角色名称">
            <el-input v-model="roleData.roleName"
                      disabled
                      placeholder="请输入角色名称"></el-input>
          </el-form-item>

          <el-form-item label="权限字符"
                        prop="postCode">
            <el-input v-model="roleData.roleKey"
                      disabled
                      placeholder="请输入权限字符"></el-input>
          </el-form-item>
          <el-form-item label="权限范围"
                        prop="dataScope">
            <el-select placeholder="请选择"
                       v-model="roleData.dataScope">
              <el-option label="全部数据权限"
                         :value="1">
              </el-option>
              <el-option label="自定义数据权限"
                         :value="2">
              </el-option>
              <el-option label="本部门数据权限"
                         :value="3">
              </el-option>

              <el-option label="本部门及一下数据权限"
                         :value="4">
              </el-option>

              <el-option label="仅本人数据权限"
                         :value="5">
              </el-option>

            </el-select>
            <el-form-item v-if="roleData.dataScope==2"
                          label="菜单权限">
              <el-checkbox v-model="unfold">展开/折叠</el-checkbox>
              <el-checkbox v-model="roleAll">全选/全不选</el-checkbox>
              <el-checkbox v-model="parent">父子联动</el-checkbox>
              <el-tree :data="deptListTree"
                       show-checkbox
                       node-key="id"
                       ref="roleTree"
                       :check-strictly="!parent"
                       :default-expand-all="false"
                       style="border:1px solid #e5e6e7"
                       highlight-current
                       :props="defaultProps">
              </el-tree>
            </el-form-item>

          </el-form-item>
        </el-form>
        <span slot="footer"
              class="dialog-footer">
          <el-button @click="roleKey = false">取 消</el-button>
          <el-button type="primary"
                     @click="updataRoleKey">确 定</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 权限
      unfold: false,
      roleAll: false,
      parent: true,
      deptListTree: [],
      roleKey: false,
      roleData: {
        admin: false,
        createBy: null,
        createTime: null,
        dataScope: null,
        delFlag: null,
        deptCheckStrictly: null,
        deptIds: [],
        flag: null,
        menuCheckStrictly: null,
        menuIds: null,
        params: {},
        remark: null,
        roleId: null,
        roleKey: null,
        roleName: null,
        roleSort: null,
        searchValue: null,
        status: '0',
        updateBy: null,
        updateTime: null
      },
      // 展开的数组
      arr: [],
      // 父子关联........
      strictly: true,
      selectAll: false,
      expand: false,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        roleName: null,
        roleKey: null,
        status: null
        // beginTime: '',
        // endTime: ''
        // params: { beginTime: '', endTime: '' }
      },
      formData: {
        roleId: null,
        deptCheckStrictly: true,
        deptIds: [],
        menuCheckStrictly: true,
        menuIds: [],
        remark: null,
        roleKey: null,
        roleName: null,
        roleSort: 0,
        status: '0'
      },
      tableData: [],
      checkItem: [],
      seltime: [],
      total: 0,
      loading: false,
      dialogVisible: false,
      flag: true,
      treeList: [],
      defaultProps: {
        children: 'children',
        label: 'label'
      }
    }
  },
  mounted() {
    this.getData()
  },
  methods: {
    async getData() {
      this.loading = true
      let { data } = await this.$axios.get('system/role/list', { params: this.queryParams })
      this.tableData = data.rows
      this.total = data.total
      this.loading = false
    },

    // 数据权限
    async roleKeyHandler(id) {
      this.roleKey = true
      let { data: res } = await this.$axios.get(`system/dept/roleDeptTreeselect/${id}`)
      let { data } = await this.$axios.get(`system/role/${id}`)
      console.log(res)
      let num = Number(data.data.dataScope)
      this.roleData = data.data
      this.roleData.dataScope = num
      this.deptListTree = res.depts
      if (data.data.dataScope != 2) return
      this.$nextTick(() => {
        this.$refs.roleTree.setCheckedKeys(res.checkedKeys)
      })
    },
    async updataRoleKey() {
      if (this.roleData.dataScope == 2) {
        this.roleData.deptIds = this.$refs.roleTree.getCheckedKeys()
      } else {
        this.roleData.deptIds = []
      }
      let num = this.roleData.dataScope.toString()
      this.roleData.dataScope = num
      let data = await this.$axios.put('system/role/dataScope', this.roleData)
      if (data.data.code != 200) return this.$message.error(data.data.msg)
      this.$message({ type: 'success', message: data.data.msg })
      this.getData()
      this.roleKey = false
    },

    //改变状态system/user/changeStatus
    treeChange(data) {},

    changeStatus(status, data) {
      this.$confirm(`确认要${status == 0 ? '启用' : '停用'}${data.roleName}用户吗?`, '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          let { data: res } = await this.$axios.put(`system/role/changeStatus`, { status: status, roleId: data.roleId })

          if (res.code != 200) {
            this.$message.error(res.msg)
            this.getData()
          } else {
            this.$message.success(res.msg)
            this.getData()
          }
        })
        .catch(() => {
          this.getData()
          this.$message({
            type: 'info',
            message: '已取消'
          })
        })
    },
    closed() {
      this.strictly = true
      this.selectAll = false
      this.expand = false
    },
    async getUser() {
      let { data } = await this.$axios.get('system/menu/treeselect/')
      this.treeList = data.data
    },

    updatadata() {
      this.updateHandler(this.checkItem[0].roleId)
    },
    async updateHandler(id) {
      this.dialogVisible = true
      this.flag = false
      this.getUser()
      let { data: res } = await this.$axios.get(`system/menu/roleMenuTreeselect/${id}`)
      let { data } = await this.$axios.get(`system/role/${id}`)

      console.log(this.$refs)
      this.formData = data.data
      // this.menuIds = res.checkedKeys

      this.$refs.tree.setCheckedKeys(res.checkedKeys)
    },
    delMore() {
      let ids = this.checkItem.map((el) => el.roleId)
      this.deleteHandler(ids)
    },
    deleteHandler(id) {
      this.$confirm(`是否确认删除编号为${id.toString()}的数据项?`, '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          let data = await this.$axios.delete(`system/role/${id.toString()}`)
          console.log(data)
          if (data.data.code != 200) return this.$message.error(data.data.msg)
          this.$message({
            type: 'success',
            message: data.data.msg
          })
          this.getData()
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          })
        })
    },

    async update() {
      this.formData.menuIds = this.$refs.tree.getCheckedKeys()
      let data = null
      this.dialogVisible = false
      if (this.formData.roleId) {
        data = await this.$axios.put('system/role', this.formData)
      } else {
        data = await this.$axios.post('system/role', this.formData)
      }
      if (data.data.code != 200) return this.$message.error(data.data.msg)
      this.$message({ type: 'success', message: data.data.msg })
      this.getData()
    },

    async addXqq() {
      this.dialogVisible = true
      let { data } = await this.$axios.get('system/menu/treeselect/')
      this.treeList = data.data
      this.$refs.tree.setCheckedKeys([])
      this.flag = true

      this.form = {
        id: null,
        value: null
      }
      this.formData = { roleId: null, deptCheckStrictly: true, deptIds: [], menuCheckStrictly: true, menuIds: [], remark: null, roleKey: null, roleName: null, roleSort: 0, status: '0' }
    },

    // 刷新
    // 刷新
    refreshTable() {
      this.loading = true
      this.queryParams = { pageNum: 1, pageSize: 10, roleName: null, roleKey: null, status: null }
      this.getData()
    },

    handleSizeChange(val) {
      this.queryParams.pageSize = val
      this.getData()
    },
    handleCurrentChange(val) {
      this.queryParams.pageNum = val
      this.getData()
    },
    handleSelectionChange(val) {
      this.checkItem = val
    },
    async exportdata() {
      this.$confirm('是否确认导出所有数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          // let data = await this.$axios.get('system/user/export', { params: this.queryParams })
          // console.log(data)
          this.getExport()
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          })
        })
    },
    async getExport() {
      let { data } = await this.$axios.get('system/role/export', { params: this.queryParams })

      if (data.code != 200) {
        this.$message.error('失败')
      } else {
        window.location.href = 'https://jumeng.xzjumeng.com/prod-api/common/download?fileName=' + encodeURI(data.msg) + '&delete=' + true
      }
    }
  },
  // 监听状态改变
  watch: {
    // 监听系统全选
    expand(val) {
      if (val) {
        for (var i in this.$refs.tree.store.nodesMap) {
          this.$refs.tree.store.nodesMap[i].expanded = true
        }
      } else {
        for (var j in this.$refs.tree.store.nodesMap) {
          this.$refs.tree.store.nodesMap[j].expanded = false
        }
      }
    },
    selectAll(val) {
      if (val) {
        this.$refs.tree.setCheckedNodes(this.treeList)
      } else {
        this.$refs.tree.setCheckedNodes([])
      }
      this.formData.menuIds = this.$refs.tree.getCheckedKeys()
      console.log(this.$refs.tree.getCheckedKeys())
    },

    unfold(val) {
      if (val) {
        for (var i in this.$refs.roleTree.store.nodesMap) {
          this.$refs.roleTree.store.nodesMap[i].expanded = true
        }
      } else {
        for (var j in this.$refs.roleTree.store.nodesMap) {
          this.$refs.roleTree.store.nodesMap[j].expanded = false
        }
      }
    },
    roleAll(val) {
      if (val) {
        this.$refs.roleTree.setCheckedNodes(this.deptListTree)
      } else {
        this.$refs.roleTree.setCheckedNodes([])
      }
      this.roleData.deptIds = this.$refs.roleTree.getCheckedKeys()
      console.log(this.$refs.roleTree.getCheckedKeys())
    }
  }
  // 监听自定义权限
}
</script>

<style lang="scss" scoped>
.btnList {
  margin-bottom: 8px;
  margin-top: 15px;
  display: flex;
  justify-content: space-between;
}
.page {
  margin-top: 15px;
  display: flex;
  justify-content: flex-end;
}
</style>